# -*- coding: utf-8 -*-

# Crispy Plotter, a fast and easy-to-use function plotter
# Copyright (C) 2010 Konrad Kölzer

# Crispy Plotter is free software, see License.txt for details.

# Conversion script for .po files
# Written by Konrad Kölzer

"""
Converts gnugettext .po files to .mo files and writes them to the target
folders specified by the domains dictionary.
gnugettext has to be installed and msgfmt command needs to be available
from shell to make this script work.
"""

import glob
import subprocess
import os.path

"""Defines domains and the target directory of converted .mo files for
that domain"""
domains = { "default" : "../bin/Locale", \
            "install" : "../install/locale" }

def processDomain(domain, targetDir):
    print('Converting .po files in domain "%s" to %s:' % (domain, targetDir))
    files = glob.glob(domain + '/*.po') + glob.glob(domain + '/*.pot')
    print('Found %d file(s)' % len(files))
    for f in files:
        dirName, fileName = os.path.split(f)
        fileName, fileExt = os.path.splitext(fileName)
        if fileName == domain:
            lang = 'en'
        else:
            parts = fileName.split('-') # split into domain and language
            lang = parts[-1]
        outDir = '%s/%s/LC_MESSAGES'  % (targetDir, lang)
        try:
            os.makedirs(os.path.abspath(outDir))
        except EnvironmentError:
            pass
        outfile = '%s/%s.mo' % (outDir, domain)
        print('Processing %s => %s' % (f, os.path.normpath(outfile)))
        args = ['msgfmt', f, '--output-file=%s' % outfile, '-v']
        p = subprocess.Popen(args, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        result = p.wait()
        if result != 0:
            print('Could not convert file "%s".' % f)

for domain, targetDir in domains.items():
    processDomain(domain, targetDir)

